package ybt.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import ybt.custom.BaseService;
import ybt.entity.SysRole;
import ybt.entity.SysUser;
import ybt.repository.SysUserRepository;
import ybt.security.User2;

@Service
public class SysUserService extends BaseService<SysUser, Integer> implements UserDetailsService{
	@Autowired
	private SysUserRepository userDAO;
	
	public SysUser login(String username, String pwd) {
		return userDAO.findByUsernameAndPassword(username,pwd);
	}
	

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user=userDAO.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException(username);
		}
		List<GrantedAuthority> authorities=new ArrayList<>();
		List<SysRole> roles = user.getRoles();
		for(SysRole role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
		return new User2(user.getUsername(),user.getPassword(),user.getName(), authorities);
	}

	/*
	 * public static void main(String[] args) { BCryptPasswordEncoder encoder=new
	 * BCryptPasswordEncoder(); String encodeCode = encoder.encode("1111");
	 * System.out.println(encodeCode);
	 * 
	 * }
	 */

}
